#include "core/drv.h"
#include "core/bus.h"

#if (DEVICE_DEBUG > DEVICE_DEBUG_OFF)
static const char *TAG = "DRIVER";
#endif

DEVICE_PUBLIC(static driver_t *) driver_table[DRIVER_NUM_MAX] = {0};

DEVICE_PUBLIC(int) driver_register(driver_t *drv, void *bus) {
    if (!drv || !drv->compat || !drv->name) {
        DEVICE_LOG_ERROR(TAG, "driver_register param invalid");
        return -1;
    }

    const int drv_max_num = DEVICE_ARRAY_SIZE(driver_table);
    for (int i = 0; i < drv_max_num; i++) {
        if (driver_table[i] == NULL) {
            if (bus_add_driver(bus, drv) != 0) {
                return -2;
            }
            driver_table[i] = drv;
            DEVICE_LOG_DEBUG(TAG, "driver[%s] register success", drv->name);
            return 0;
        }
    }
    DEVICE_LOG_ERROR(TAG, "driver[%s] register error, driver table full", drv->name);
    return -3;
}

DEVICE_PUBLIC(int) driver_unregister(driver_t *drv) {
    if (!drv || !drv->bus || !drv->compat || !drv->name) {
        DEVICE_LOG_ERROR(TAG, "driver_unregister param invalid");
        return -1;
    }
    const int drv_max_num = DEVICE_ARRAY_SIZE(driver_table);
    for (int i = 0; i < drv_max_num; i++) {
        if (driver_table[i] == drv) {
            if (bus_remove_driver(drv->bus, drv) != 0) {
                return -2;
            }
            driver_table[i] = NULL;
            DEVICE_LOG_DEBUG(TAG, "driver[%s] unregister success", drv->name);
            return 0;
        }
    }
    DEVICE_LOG_ERROR(TAG, "driver[%s] unregister error, driver not found", drv->name);
    return -3;
}
